package yang.itcode.service.impl;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yang.itcode.exception.BusinessException;
import yang.itcode.mapper.CategoryMapper;
import yang.itcode.mapper.InventoryDetailMapper;
import yang.itcode.mapper.ProductMapper;
import yang.itcode.model.pojo.Category;
import yang.itcode.model.pojo.InventoryDetail;
import yang.itcode.model.pojo.Product;
import yang.itcode.service.CategoryService;
import yang.itcode.service.ProductService;
import yang.itcode.utils.ThreadUtil;

import java.math.BigDecimal;
import java.util.List;

import static yang.itcode.constant.ErrorConstant.*;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private InventoryDetailMapper inventoryDetailMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryService categoryService;

    @Override
    public boolean addProduct(JSONObject obj) {
        String code = obj.getStr("code");
        String name = obj.getStr("name");
        String brand = obj.getStr("brand");
        String model = obj.getStr("model");
        String unit = obj.getStr("unit");
        BigDecimal purchasePrice = obj.getBigDecimal("purchasePrice");
        BigDecimal salePrice = obj.getBigDecimal("salePrice");
        String image = obj.getStr("image");
        Integer categoryId = obj.getInt("categoryId");
        Integer userId = ThreadUtil.getCurrentId();
        if (code == null || name == null || categoryId == null || unit == null) {
            throw new BusinessException(PRODUCT_PARAM_EXCEPTION_CODE, PRODUCT_PARAM_EXCEPTION_MESSAGE);
        }
        Product product = new Product();
        product.setCode(code);
        product.setName(name);
        product.setBrand(brand);
        product.setModel(model);
        product.setUnit(unit);
        product.setPurchasePrice(purchasePrice);
        product.setSalePrice(salePrice);
        product.setImage(image);
        product.setCategoryId(categoryId);
        product.setCreateUserId(userId);
        product.setUpdateUserId(userId);
        return productMapper.insert(product) == 1;
    }

    @Override
    public PageInfo<JSONObject> getProductList(Integer pageNum, Integer pageSize, JSONObject condition) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        condition.set("status", 1);
        if(condition.getInt("categoryIds") != null) {
            List<Category> list = categoryService.getCategoryWithDescendants(condition.getInt("categoryIds"));
            // 使用stream流提取ID列表
            List<Integer> categoryIds = list.stream().map(Category::getId).toList();
            condition.set("categoryIds", categoryIds);
        }
        return new PageInfo<>(productMapper.selectProductView(condition));
    }

    @Override
    public JSONObject getProductDetail(Integer id) {
        JSONObject obj = new JSONObject();
        // 构建商品基础信息
        Product product = productMapper.selectById(id);
        if (product == null || product.getStatus() != 1) {
            throw new BusinessException(PRODUCT_NOT_EXIST_EXCEPTION_CODE, PRODUCT_NOT_EXIST_EXCEPTION_MESSAGE);
        }
        obj.set("id", product.getId());
        obj.set("code", product.getCode());
        obj.set("name", product.getName());
        obj.set("brand", product.getBrand());
        obj.set("model", product.getModel());
        obj.set("unit", product.getUnit());
        obj.set("purchasePrice", product.getPurchasePrice());
        obj.set("salePrice", product.getSalePrice());
        obj.set("image", product.getImage());
        obj.set("categoryId", product.getCategoryId());
        // 构建商品库存信息
        JSONObject condition = new JSONObject();
        condition.set("productId", id);
        condition.set("status", 1);
        condition.set("orderBy", "create_time");
        condition.set("sortOrder", "desc");
        PageHelper.startPage(1, 1);
        List<InventoryDetail> list = inventoryDetailMapper.selectByCondition(condition);
        if (list.size() > 0) {
            InventoryDetail inventoryDetail = list.get(0);
            obj.set("balanceQuantity", inventoryDetail.getBalanceQuantity());
            obj.set("currentAvgCost", inventoryDetail.getCurrentAvgCost());
        } else {
            obj.set("balanceQuantity", 0);
            obj.set("currentAvgCost", 0);
        }
        // 构建商品分类信息
        Category category = categoryMapper.selectById(product.getCategoryId());
        if (category != null) {
            obj.set("categoryName", category.getName());
        } else {
            obj.set("categoryName", null);
        }
        return obj;
    }

    @Override
    public boolean updateProduct(JSONObject obj) {
        String code = obj.getStr("code");
        String name = obj.getStr("name");
        String brand = obj.getStr("brand");
        String model = obj.getStr("model");
        String unit = obj.getStr("unit");
        BigDecimal purchasePrice = obj.getBigDecimal("purchasePrice");
        BigDecimal salePrice = obj.getBigDecimal("salePrice");
        String image = obj.getStr("image");
        Integer categoryId = obj.getInt("categoryId");
        Integer id = obj.getInt("id");
        if (code == null || name == null || categoryId == null || unit == null || id == null) {
            throw new BusinessException(PRODUCT_PARAM_EXCEPTION_CODE, PRODUCT_PARAM_EXCEPTION_MESSAGE);
        }
        Integer userId = ThreadUtil.getCurrentId();
        Product product = new Product();
        product.setId(id);
        product.setCode(code);
        product.setName(name);
        product.setBrand(brand);
        product.setModel(model);
        product.setUnit(unit);
        product.setPurchasePrice(purchasePrice);
        product.setSalePrice(salePrice);
        product.setImage(image);
        product.setCategoryId(categoryId);
        product.setUpdateUserId(userId);
        return productMapper.update(product) == 1;
    }

    @Override
    public boolean deleteProduct(Integer id) {
        Integer userId = ThreadUtil.getCurrentId();
        Product product = new Product();
        product.setId(id);
        product.setStatus(0);
        product.setUpdateUserId(userId);
        return productMapper.update(product) == 1;
    }
}
